"=============================================================================
" vim 内置配置 
"==============================================================================

" 设置 vimrc 修改保存后立刻生效，不用在重新打开
" 建议配置完成后将这个关闭
" autocmd BufWritePost $MYVIMRC source $MYVIMRC
" 设置编码
set encoding=utf8
" 字体
" set guifont=DroidSansMono\ Nerd\ Font\ 11
" 关闭兼容模式
set nocompatible
set nu " 设置行号
set cursorline "突出显示当前行
" set cursorcolumn " 突出显示当前列
" 显示相对行号
set relativenumber
" 取消相对行号
"set norelativenumber

set showmatch " 显示括号匹配

" tab 缩进
set tabstop=4 " 设置Tab长度为4空格
set shiftwidth=4 " 设置自动缩进长度为4空格
set autoindent " 继承前一行的缩进方式，适用于多行注释
set smarttab  " 开启新行时使用智能tab 缩进
" 设置空白字符的视觉提示
set list listchars=extends:❯,precedes:❮,tab:▸\ ,trail:˽

" 定义快捷键的前缀，即<Leader>
" let mapleader=" " 


" ==== 系统剪切板复制粘贴 ====
" v 模式下复制内容到系统剪切板
vmap <space>ec "+yy
" n 模式下复制一行到系统剪切板
nmap <space>ec "+yy
" n 模式下粘贴系统剪切板的内容
nmap <space>ev "+p

" 开启实时搜索
set incsearch
" 搜索时大小写不敏感
" set ignorecase
syntax enable
syntax on                    " 开启文件类型侦测
filetype plugin indent on    " 启用自动补全

" 退出插入模式指定类型的文件自动保存
au InsertLeave *.go,*.sh,*.java write

"==============================================================================
" 插件开始的位置
"==============================================================================

" 为插件指定一个目录
" - For Neovim: stdpath('data') . '/plugged'
" - Avoid using standard Vim directory names like 'plugin' 避免使用标准的Vim目录名，如'plugin'
call plug#begin('~/.vim/plugged')

" 确保使用单引号

" 可以快速对齐的插件;  简化符号Shorthand notation; 获取fetches https://github.com/junegunn/vim-easy-align
Plug 'junegunn/vim-easy-align'

" 自动补全括号的插件，包括小括号，中括号，以及花括号
Plug 'jiangmiao/auto-pairs'

" Any valid git URL is allowed 允许任何有效的git URL
Plug 'https://github.com/junegunn/vim-github-dashboard.git'

" Multiple Plug commands can be written in a single line using | separators 使用|分隔符可以在一行中编写多个插头命令
Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'

" Vim状态栏插件，包括显示行号，列号，文件类型，文件名，以及Git状态
Plug 'vim-airline/vim-airline'

" 代码自动完成，安装完插件还需要额外配置才可以使用
"Plug 'Valloric/YouCompleteMe'
" 赵启明大佬 nodejs 写的补全插件
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" 异步的错误处理的插件
Plug 'dense-analysis/ale'
" 下面两个插件要配合使用，可以自动生成代码块
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'

" 可以在 vim 中使用 tab 补全
" Plug 'vim-scripts/SuperTab'

" 可以在 vim 中自动完成
Plug 'Shougo/neocomplete.vim'

"快速注释
Plug 'preservim/nerdcommenter'


" 用来提供一个导航目录的侧边栏 ; 插件 On-demand loading 按需加载
Plug 'scrooloose/nerdtree', { 'on':  'NERDTreeToggle' }
" 给文件添加图标
Plug 'ryanoasis/vim-devicons'
" 与vim-devicons一起使用，为图标或整个标签添加颜色
Plug 'tiagofumo/vim-nerdtree-syntax-highlight'
Plug 'tpope/vim-fireplace', { 'for': 'clojure' }

" 可以使 nerdtree 的 tab 更加友好些
Plug 'jistr/vim-nerdtree-tabs'

" 可以在导航目录中看到 git 版本信息
Plug 'Xuyuanp/nerdtree-git-plugin'

" 可以在文档中显示 git 信息
Plug 'airblade/vim-gitgutter'

" Using a non-master branch 使用非主分支
Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }

" 查看当前代码文件中的变量和函数列表的插件，
" 可以切换和跳转到代码中对应的变量和函数的位置
" 大纲式导航, Go 需要 https://github.com/jstemmer/gotags 支持
Plug 'majutsushi/tagbar'

" ranger 文件浏览器 
Plug 'kevinhwang91/rnvimr', { 'branch': 'main' }

" 自动代码折叠
Plug 'Konfekt/FastFold'
" 终端增强
Plug 'wincent/terminus'

" 使用标记版本;允许通配符(要求git 1.9.2或更高版本)
" Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
" Plug 'fatih/vim-go', { 'tag': '*' }
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' }

" A Vim plugin for Meson build system
Plug 'igankevich/mesonic'

" go 中的代码追踪，输入 gd 就可以自动跳转
Plug 'dgryski/vim-godef'
" 代码自动格式化
Plug 'Chiel92/vim-autoformat'
" Plugin options 插件选项
Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }

" 自动异步生成 tags 文件
Plug 'ludovicchabant/vim-gutentags'

"　外部插件 与更新后处理钩
" Plugin outside ~/.vim/plugged with post-update hook
" Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
" Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'

" 非托管插件(手动安装和更新)
" Unmanaged plugin (manually installed and updated)
" Plug '~/my-prototype-plugin'
" yang 语法高亮
" Plug 'nathanalderson/yang.vim'
" vim 快速移动
Plug 'easymotion/vim-easymotion'

" 代码颜色
" toml文件语法高亮
Plug 'cespare/vim-toml', { 'branch': 'main' }
" Bookmarks
Plug 'MattesGroeger/vim-bookmarks'

" 在浮动/弹出窗口中使用（neo）vim终端。
Plug 'voldikss/vim-floaterm'
" 成对编辑
Plug 'tpope/vim-surround'

" 禅模式
Plug 'junegunn/goyo.vim'
" 聚光灯 
Plug 'junegunn/limelight.vim'

" 该插件为Vim和Neovim提供了一个开始屏幕
Plug 'mhinz/vim-startify'


" 配色方案
" colorscheme neodark
Plug 'KeitaNakamura/neodark.vim'
" colorscheme monokai
Plug 'crusoexia/vim-monokai'
" colorscheme github
Plug 'acarapetis/vim-colors-github'
" colorscheme one
Plug 'rakr/vim-one'
" colorscheme gruvbox
Plug 'morhetz/gruvbox'
" colorscheme night-owl
Plug 'haishanh/night-owl.vim'


" 通用debug 
Plug 'puremourning/vimspector'

" 插件结束的位置，插件全部放在此行上面
call plug#end()

"==============================================================================
" 主题配色
"==============================================================================

" 开启24bit的颜色，开启这个颜色会更漂亮一些
set termguicolors
" 配色方案, 可以从上面插件安装中的选择一个使用
" colorscheme gruvbox  " 主题
colorscheme night-owl
" To enable the lightline theme
let g:lightline = { 'colorscheme': 'nightowl' }
set background=dark  " 主题背景 dark-深色; light-浅色

" 透明 
highlight Normal guibg=NONE ctermbg=None



""""" enable 24bit true color
" If you have vim >=8.0 or Neovim >= 0.1.5
if (has("termguicolors"))
	set termguicolors
endif
" For Neovim 0.1.3 and 0.1.4
let $NVIM_TUI_ENABLE_TRUE_COLOR=1

"==============================================================================
" Chiel92/vim-autoformat 插件
"==============================================================================
let g:autoformat_verbosemode=1 "开启详细模式便于查错
"设置发生保存事件时执行格式化
autocmd BufWrite *.go,*.c*.py,*.java,*.sh,*.json,*.js,*.html,*.css,*.gradle,*.sql,*.xml,*.yml :Autoformat 

"let g:autoformat_autoindent = 0
"let g:autoformat_retab = 0
"let g:autoformat_remove_trailing_spaces = 0
"autocmd FileType vim,tex let b:autoformat_autoindent=0
"gg=G :retab :RemoveTrailingSpaces

"==============================================================================
" vim-go 插件
"==============================================================================
let g:go_fmt_command = "goimports" " 格式化将默认的 gofmt 替换
let g:go_autodetect_gopath = 1
let g:go_list_type = "quickfix"


let g:godef_split=2
let g:go_auto_type_info                      = 1
let g:go_highlight_array_whitespace_error    = 1
let g:go_highlight_build_constraints         = 1
let g:go_highlight_chan_whitespace_error     = 1
let g:go_highlight_extra_types               = 1
let g:go_highlight_fields                    = 1
let g:go_highlight_format_strings            = 1
let g:go_highlight_function_calls            = 1
let g:go_highlight_function_parameters       = 1
let g:go_highlight_functions                 = 1
let g:go_highlight_generate_tags             = 1
let g:go_highlight_methods                   = 1
let g:go_highlight_operators                 = 1
let g:go_highlight_space_tab_error           = 1
let g:go_highlight_string_spellcheck         = 1
let g:go_highlight_structs                   = 1
let g:go_highlight_trailing_whitespace_error = 1
let g:go_highlight_types                     = 1
let g:go_def_mapping_enabled                 = 0
let g:go_doc_keywordprg_enabled              = 0
let g:go_imports_autosave                    = 1
let g:go_fmt_autosave                        = 1
let g:go_mod_fmt_autosave                    = 1
let g:go_version_warning                     = 1
let g:go_fmt_experimental                    = 1
"let g:go_metalinter_autosave                 = 1
"let g:go_metalinter_autosave_enabled         = ['vet', 'golint']
autocmd FileType go noremap gk :GoDoc<CR>
autocmd FileType go noremap gta :GoTest<CR>
autocmd FileTYpe go noremap gtt :GoTestFunc<CR>

"==============================================================================
" NERDTree 插件
"==============================================================================

" 打开和关闭NERDTree快捷键
" map <F10> :NERDTreeToggle<CR>
noremap <space>wt  :NERDTreeToggle<CR>
noremap <space>wtf :NERDTreeFind<CR>
" 显示行号
let NERDTreeShowLineNumbers=1
" 打开文件时是否显示目录
let NERDTreeAutoCenter=1
let g:NERDTreeDirArrowExpandable = '▸'
let g:NERDTreeDirArrowCollapsible = '▾'
" 是否显示隐藏文件
let NERDTreeShowHidden=0
" 设置宽度
" let NERDTreeWinSize=31
" 开启Nerdtree时自动显示Bookmarks
let NERDTreeShowBookmarks=1
" 是否显示行号
"let g:NERDTreeShowLineNumbers=1
" 忽略一下文件的显示
let NERDTreeIgnore=['\.pyc','\~$','\.swp','\.vscode','\.idea','__pycache__']
" 打开 vim 文件及显示书签列表
let NERDTreeShowBookmarks=2
"打开vim时如果没有文件自动打开NERDTree
 " autocmd vimenter * if !argc()|NERDTree|endif
"当NERDTree为剩下的唯一窗口时自动关闭
 autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
" autocmd BufEnter * if winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | quit | endif
" 如何防止其他缓冲区替换其窗口中的 NERDTree？
" 如果另一个缓冲区试图替换 NERDTree，请将其放在另一个窗口中，并带回 NERDTree。
" autocmd BufEnter * if bufname('#') =~ 'NERD_tree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 |
    " \ let buf=bufnr() | buffer# | execute "normal! \<C-W>w" | execute 'buffer'.buf | endif

" 在终端启动vim时，共享NERDTree
let g:nerdtree_tabs_open_on_console_startup=1

" Vim 启动时如何自动打开 NERDTree？
" 开始NERDTree和光标停留在它
" autocmd VimEnter * NERDTree

" 开始NERDTree，放在其他窗口的光标回来。
" autocmd VimEnter * NERDTree | wincmd p

" Start NERDTree, unless a file or session is specified, eg. vim -S session_file.vim.
" autocmd StdinReadPre * let s:std_in=1
" autocmd VimEnter * if argc() == 0 && !exists('s:std_in') && v:this_session == '' | NERDTree | endif

" Start NERDTree when Vim starts with a directory argument.
" autocmd StdinReadPre * let s:std_in=1
" autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists('s:std_in') |
 " \ execute 'NERDTree' argv()[0] | wincmd p | enew | execute 'cd '.argv()[0] | endif


" NERDTreeFind 查找当前文件所在节点

"==============================================================================
"  majutsushi/tagbar 插件
"==============================================================================

" majutsushi/tagbar 插件打开关闭快捷键
" nmap <F9> :TagbarToggle<CR>
noremap <space>wf :TagbarToggle<CR>

let g:tagbar_type_go = {
			\ 'ctagstype' : 'go',
			\ 'kinds'     : [
			\ 'p:package',
			\ 'i:imports:1',
			\ 'c:constants',
			\ 'v:variables',
			\ 't:types',
			\ 'n:interfaces',
			\ 'w:fields',
			\ 'e:embedded',
			\ 'm:methods',
			\ 'r:constructor',
			\ 'f:functions'
			\ ],
			\ 'sro' : '.',
			\ 'kind2scope' : {
			\ 't' : 'ctype',
			\ 'n' : 'ntype'
			\ },
			\ 'scope2kind' : {
			\ 'ctype' : 't',
			\ 'ntype' : 'n'
			\ },
			\ 'ctagsbin'  : 'gotags',
			\ 'ctagsargs' : '-sort -silent'
			\ }


"==============================================================================
"  nerdtree-git-plugin 插件
"==============================================================================
let g:NERDTreeIndicatorMapCustom = {
			\ "Modified"  : "✹",
			\ "Staged"    : "✚",
			\ "Untracked" : "✭",
			\ "Renamed"   : "➜",
			\ "Unmerged"  : "═",
			\ "Deleted"   : "✖",
			\ "Dirty"     : "✗",
			\ "Clean"     : "✔︎",
			\ 'Ignored'   : '☒',
			\ "Unknown"   : "?"
			\ }

" let g:NERDTreeGitStatusShowIgnored

"==============================================================================
"  tiagofumo/vim-nerdtree-syntax-highlight 插件
"==============================================================================

let s:brown = "905532"
let s:aqua =  "3AFFDB"
let s:blue = "689FB6"
let s:darkBlue = "44788E"
let s:purple = "834F79"
let s:lightPurple = "834F79"
let s:red = "AE403F"
let s:beige = "F5C06F"
let s:yellow = "F09F17"
let s:orange = "D4843E"
let s:darkOrange = "F16529"
let s:pink = "CB6F6F"
let s:salmon = "EE6E73"
let s:green = "8FAA54"
let s:lightGreen = "31B53E"
let s:white = "FFFFFF"
let s:rspec_red = 'FE405F'
let s:git_orange = 'F54D27'
let g:NERDTreeExtensionHighlightColor = {} " this line is needed to avoid error
let g:NERDTreeExtensionHighlightColor['css'] = s:blue " sets the color of css files to blue

let g:NERDTreeExactMatchHighlightColor = {} " this line is needed to avoid error
let g:NERDTreeExactMatchHighlightColor['.gitignore'] = s:git_orange " sets the color for .gitignore files

let g:NERDTreePatternMatchHighlightColor = {} " this line is needed to avoid error
let g:NERDTreePatternMatchHighlightColor['.*_spec\.rb$'] = s:rspec_red " sets the color for files ending with _spec.rb

"let g:NERDTreeDisableFileExtensionHighlight = 1
"let g:NERDTreeDisableExactMatchHighlight = 1
"let g:NERDTreeDisablePatternMatchHighlight = 1
let g:NERDTreeFileExtensionHighlightFullName = 1
let g:NERDTreeExactMatchHighlightFullName = 1
let g:NERDTreePatternMatchHighlightFullName = 1
let g:NERDTreeHighlightFolders = 1 " enables folder icon highlighting using exact match
let g:NERDTreeHighlightFoldersFullName = 1 " highlights the folder name
" disabling Cursorline highlight from NERDTree fixed
let g:NERDTreeHighlightCursorline = 0
"==============================================================================
"  Valloric/YouCompleteMe 插件
"==============================================================================

" make YCM compatible with UltiSnips (using supertab)
"let g:ycm_key_list_select_completion = ['<C-n>', '<space>']
"let g:ycm_key_list_previous_completion = ['<C-p>', '<Up>']
"let g:SuperTabDefaultCompletionType = '<C-n>'

" better key bindings for UltiSnipsExpandTrigger
"let g:UltiSnipsExpandTrigger = "<tab>"
"let g:UltiSnipsJumpForwardTrigger = "<tab>"
"let g:UltiSnipsJumpBackwardTrigger = "<s-tab>"


"==============================================================================
"  preservim/nerdcommenter 高效率注释插件
"==============================================================================
" let mapleader="\\" 
" 默认情况下，在注释分隔符之后添加空格
let g:NERDSpaceDelims = 1
" 启用NERDCommenterToggle以检查所有选定的行是否已注释
let g:NERDToggleCheckAllLines = 1
" 注视方式
" ca 切换注释方式 //与 /***/
" cc 注释当前行
" cy 和cc作用相同，区别在于先复制要注释的行
" c 空格 切换注释与非注释
" cu 取消注释
" cA 行尾注释并进入插入模式
" cs 性感块注释
" cm 如果可能的话，用多个分隔符来注释给出的行
" ci 分开切换选定行的注释状态，每一个选定行如果被注释了，那么取消注释，反之亦然
" <leader> c$ 注释当前行从光标到行尾
" [count]<leader>cl
" [count]<leader>cb
" [count] <leader>cb
" 和cc作用相同，区别在于分隔符左对齐（cl），右对齐（cr），中间对齐（cb）
" normal 6,cs 从当前行开始注释6行 
"==============================================================================
"  dense-analysis/ale异步的错误处理的插件
"==============================================================================
let g:ale_set_highlights = 1
let g:ale_set_quickfix = 1
"自定义error和warning图标
let g:ale_sign_error = '✗'
let g:ale_sign_warning = ''
"在vim自带的状态栏中整合ale
let g:ale_statusline_format = ['✗ %d', ' %d', '✔ OK']
"显示Linter名称,出错或警告等相关信息
let g:ale_echo_msg_error_str = 'E'
let g:ale_echo_msg_warning_str = 'W'
let g:ale_echo_msg_format = '[%linter%] %s [%severity%]'
"打开文件时不进行检查
let g:ale_lint_on_enter = 1

"普通模式下，sp前往上一个错误或警告，sn前往下一个错误或警告
nmap sp <Plug>(ale_previous_wrap)
nmap sn <Plug>(ale_next_wrap)
"<Leader>s触发/关闭语法检查
nmap <Leader>l :ALEToggle<CR>
"<Leader>d查看错误或警告的详细信息
nmap <Leader>d :ALEDetail<CR>
let g:ale_linters = {
			\ 'go': ['golint', 'go vet', 'go fmt'],
			\ }

"==============================================================================
"  neoclide/coc.nvim自动补全插件
"==============================================================================
"
"coc marketplace 插件市场
"CocInstall coc-marketplace

" 自动安装coc 拓展

let g:coc_global_extensions = [
            \ 'coc-actions',
			\ 'coc-tag',
            \ 'coc-diagnostic',
            \ 'coc-tsserver',
            \ 'coc-pyright',
            \ 'coc-rls',
            \ 'coc-html',
            \ 'coc-css',
            \ 'coc-json',
            \ 'coc-java',
            \ 'coc-java-lombok',
            \ 'coc-java-vimspector',
            \ 'coc-vimlsp',
            \ 'coc-lists',
            \ 'coc-emmet',
            \ 'coc-vetur',
            \ 'coc-yank',
            \ 'coc-git',
            \ 'coc-go',
            \ 'coc-xml',
            \ 'coc-sql',
            \ 'coc-sh',
            \ 'coc-floaterm',
            \ 'coc-fzf-preview',
            \ 'coc-clangd',
            \ 'coc-cmake',
            \ 'coc-calc',
            \ 'coc-gitignore',
            \ 'coc-explorer',
            \ 'coc-snippets',
            \ 'coc-highlight',
            \ 'coc-translator',
            \ 'coc-pairs']
" if hidden is not set, TextEdit might fail. 允许未保存文件在缓冲区中
set hidden

" Some servers have issues with backup files, see #649 关闭备份 这个issues
" 已经被关闭了可以不用设置
" set nobackup
" set nowritebackup

" Better display for messages 已经有浮动窗口了，现在还设置只会让编辑器少一行
" set cmdheight=2

" You will have bad experience for diagnostic messages when it's default 4000.
" 响应速度
set updatetime=300

" don't give |ins-completion-menu| messages.
" 补全的时候信息栏少打出一些无用的信息
set shortmess+=c

" always show signcolumns
set signcolumn=yes

" Use tab for trigger completion with characters ahead and navigate.
" Use command ':verbose imap <tab>' to make sure tab is not mapped by other plugin.
inoremap <silent><expr> <TAB>
			\ pumvisible() ? "\<C-n>" :
			\ <SID>check_back_space() ? "\<TAB>" :
			\ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"

function! s:check_back_space() abort
	let col = col('.') - 1
	return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
inoremap <silent><expr> <c-space> coc#refresh()

" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current position.
" Coc only does snippet and additional edit on confirm.
inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
" Or use `complete_info` if your vim support it, like:
" inoremap <expr> <cr> complete_info()["selected"] != "-1" ? "\<C-y>" : "\<C-g>u\<CR>"

" Use `[g` and `]g` to navigate diagnostics
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" Remap keys for gotos
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window
nnoremap <silent> K :call <SID>show_documentation()<CR>

function! s:show_documentation()
	if (index(['vim','help'], &filetype) >= 0)
		execute 'h '.expand('<cword>')
	else
		call CocAction('doHover')
	endif
endfunction

" Highlight symbol under cursor on CursorHold
autocmd CursorHold * silent call CocActionAsync('highlight')

" Remap for rename current word
nmap <leader>rn <Plug>(coc-rename)

" Remap for format selected region
xmap <leader>f  <Plug>(coc-format-selected)
nmap <leader>f  <Plug>(coc-format-selected)

augroup mygroup
	autocmd!
	" Setup formatexpr specified filetype(s).
	autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
	" Update signature help on jump placeholder
	autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Remap for do codeAction of selected region, ex: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap for do codeAction of current line
nmap <leader>ac  <Plug>(coc-codeaction)
" Fix autofix problem of current line
nmap <leader>qf  <Plug>(coc-fix-current)

" Create mappings for function text object, requires document symbols feature of languageserver.
xmap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap if <Plug>(coc-funcobj-i)
omap af <Plug>(coc-funcobj-a)

" Use <TAB> for select selections ranges, needs server support, like: coc-tsserver, coc-python
nmap <silent> <TAB> <Plug>(coc-range-select)
xmap <silent> <TAB> <Plug>(coc-range-select)

" Use `:Format` to format current buffer
command! -nargs=0 Format :call CocAction('format')

" Use `:Fold` to fold current buffer
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" use `:OR` for organize import of current buffer
command! -nargs=0 OR   :call     CocAction('runCommand', 'editor.action.organizeImport')

" Add status line support, for integration with other plugin, checkout `:h coc-status`
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Using CocList
" Show all diagnostics
nnoremap <silent> <space>ca  :<C-u>CocList diagnostics<cr>
" Manage extensions
nnoremap <silent> <space>ce  :<C-u>CocList extensions<cr>
" Show commands
nnoremap <silent> <space>cc  :<C-u>CocList commands<cr>
" Find symbol of current document
nnoremap <silent> <space>co  :<C-u>CocList outline<cr>
" Search workspace symbols
noremap <silent> <space>cs  :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent> <space>cj  :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent> <space>ck  :<C-u>CocPrev<CR>
" Resume latest coc list
nnoremap <silent> <space>cp  :<C-u>CocListResume<CR>
"==============================================================================
" fzf模糊查询文件
"==============================================================================
set rtp+=/bin/fzf
set rtp+=/home/sky/.fzf
" 始终在右侧以60％的宽度启用预览窗口
let g:fzf_preview_window = 'right:60%'
" [[缓冲区]如果可能的话，跳转到现有窗口
let g:fzf_buffers_jump = 1
" [B]提交]自定义'git log'使用的选项
let g:fzf_commits_log_options = '--graph --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr"'


command! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)

noremap <space>ff :Files<CR>
noremap <space>fc :Ag<CR>
noremap <space>fh :History<CR>
noremap <space>fl :Rg<CR>
noremap <space>fb :Buffers<CR>
noremap <space>fk :Maps<CR>
noremap <space>fm :Marks<CR>



"==============================================================================
" easymotion/vim-easymotion vim 快速移动 
"==============================================================================


" 使用 ss 启用
nmap ss <Plug>(easymotion-s2)
let g:EasyMotion_do_mapping = 0 " Disable default mappings

" 使用一个字跳转到任何你想去的地方 
" `s{char}{label}`
" nmap s <Plug>(easymotion-overwin-f)
" or
" `s{char}{char}{label}`
" Need one more keystroke, but on average, it may be more comfortable.
" nmap s <Plug>(easymotion-overwin-f2)

" Turn on case-insensitive feature
" let g:EasyMotion_smartcase = 1

" JK motions: Line motions
" map <Leader>j <Plug>(easymotion-j)
" map <Leader>k <Plug>(easymotion-k)

"==============================================================================
" kevinhwang91/rnvimr 文件浏览器
"==============================================================================

" Make Ranger replace Netrw and be the file explorer
let g:rnvimr_enable_ex = 1

" Make Ranger to be hidden after picking a file
let g:rnvimr_enable_picker = 1

" Disable a border for floating window
let g:rnvimr_draw_border = 0

" Hide the files included in gitignore
let g:rnvimr_hide_gitignore = 1

" Change the border's color
let g:rnvimr_border_attr = {'fg': 14, 'bg': -1}

" Make Neovim wipe the buffers corresponding to the files deleted by Ranger
let g:rnvimr_enable_bw = 1

" Set up only two columns in miller mode and draw border with both
let g:rnvimr_ranger_cmd = 'ranger --cmd="set column_ratios 1,1"
            \ --cmd="set draw_borders both"'

" Link CursorLine into RnvimrNormal highlight in the Floating window
highlight link RnvimrNormal CursorLine

nnoremap <silent> <M-o> :RnvimrToggle<CR>
tnoremap <silent> <M-o> <C-\><C-n>:RnvimrToggle<CR>

" Resize floating window by all preset layouts
tnoremap <silent> <M-i> <C-\><C-n>:RnvimrResize<CR>

" Resize floating window by special preset layouts
tnoremap <silent> <M-l> <C-\><C-n>:RnvimrResize 1,8,9,11,5<CR>

" Resize floating window by single preset layout
tnoremap <silent> <M-y> <C-\><C-n>:RnvimrResize 6<CR>

" Map Rnvimr action
let g:rnvimr_action = {
            \ '<C-t>': 'NvimEdit tabedit',
            \ '<C-x>': 'NvimEdit split',
            \ '<C-v>': 'NvimEdit vsplit',
            \ 'gw': 'JumpNvimCwd',
            \ 'yw': 'EmitRangerCwd'
            \ }

" Customize the initial layout
let g:rnvimr_layout = { 'relative': 'editor',
            \ 'width': float2nr(round(0.6 * &columns)),
            \ 'height': float2nr(round(0.6 * &lines)),
            \ 'col': float2nr(round(0.2 * &columns)),
            \ 'row': float2nr(round(0.2 * &lines)),
            \ 'style': 'minimal' }

" Customize multiple preset layouts
" '{}' represents the initial layout
let g:rnvimr_presets = [
            \ {},
            \ {'width': 0.700, 'height': 0.700},
            \ {'width': 0.800, 'height': 0.800},
            \ {'width': 0.950, 'height': 0.950},
            \ {'width': 0.500, 'height': 0.500, 'col': 0, 'row': 0},
            \ {'width': 0.500, 'height': 0.500, 'col': 0, 'row': 0.5},
            \ {'width': 0.500, 'height': 0.500, 'col': 0.5, 'row': 0},
            \ {'width': 0.500, 'height': 0.500, 'col': 0.5, 'row': 0.5},
            \ {'width': 0.500, 'height': 1.000, 'col': 0, 'row': 0},
            \ {'width': 0.500, 'height': 1.000, 'col': 0.5, 'row': 0},
            \ {'width': 1.000, 'height': 0.500, 'col': 0, 'row': 0},
            \ {'width': 1.000, 'height': 0.500, 'col': 0, 'row': 0.5}]

"==============================================================================
"  junegunn/limelight.vim插件配置
"==============================================================================
" Color name (:help cterm-colors) or ANSI code
" let g:limelight_conceal_ctermfg = 'gray'
" let g:limelight_conceal_ctermfg = 240

" Color name (:help gui-colors) or RGB color
" let g:limelight_conceal_guifg = 'DarkGray'
" let g:limelight_conceal_guifg = '#777777'

" Default: 0.5
" let g:limelight_default_coefficient = 0.7

" Number of preceding/following paragraphs to include (default: 0)
" let g:limelight_paragraph_span = 1

" Beginning/end of paragraph
"   When there's no empty line between the paragraphs
"   and each paragraph starts with indentation
" let g:limelight_bop = '^\s'
" let g:limelight_eop = '\ze\n^\s'

" Highlighting priority (default: 10)
"   Set it to -1 not to overrule hlsearch
" let g:limelight_priority = -1



" active key

nmap <space>wn :Limelight<CR>
xmap <space>wn :Limelight<CR>




"==============================================================================
"  junegunn/goyo.vim插件配置
"==============================================================================

let s:save_option = {}
function! s:goyo_enter()
  let s:save_option['showmode'] = &showmode
  let s:save_option['showcmd'] = &showcmd
  let s:save_option['scrolloff'] = &scrolloff
  set noshowmode
  set noshowcmd
  set scrolloff=999
  if exists(':Limelight') == 2
    Limelight
    let s:save_option['limelight'] = 1
  endif
endfunction

function! s:goyo_leave()
  let &showmode = s:save_option['showmode']
  let &showcmd = s:save_option['showcmd']
  let &scrolloff = s:save_option['scrolloff']
  if get(s:save_option,'limelight', 0)
    execute 'Limelight!'
  endif
endfunction
augroup goyo_map
  autocmd! User GoyoEnter nested call <SID>goyo_enter()
  autocmd! User GoyoLeave nested call <SID>goyo_leave()
augroup END

" vim:set et sw=2:


"limelight
"<Leader>l触发limelight功能
nmap <space>wl :Goyo<CR>
xmap <space>wl :Goyo<CR>
"进入goyo模式后自动触发limelight,退出后则关闭
autocmd! User GoyoEnter Limelight
autocmd! User GoyoLeave Limelight!
"==============================================================================
"  vim-bookmarks插件配置
"==============================================================================
let g:bookmark_no_default_key_mappings = 1
" 添加普通书签
nmap mt <Plug>BookmarkToggle
" 添加带描述的书签
nmap ma <Plug>BookmarkAnnotate
" 查看所有书签
nmap ml <Plug>BookmarkShowAll
" 跳转到下一个书签
nmap mi <Plug>BookmarkNext
" 跳转到上一个书签
nmap mn <Plug>BookmarkPrev
" 清除当前所有书签
nmap mC <Plug>BookmarkClear
" 清除所有书签
nmap mX <Plug>BookmarkClearAll
nmap mu <Plug>BookmarkMoveUp
nmap me <Plug>BookmarkMoveDown
nmap <LEADER>g <Plug>BookmarkMoveToLine
let g:bookmark_save_per_working_dir = 1
let g:bookmark_auto_save = 1
let g:bookmark_manage_per_buffer = 1
let g:bookmark_save_per_working_dir = 1
let g:bookmark_center = 1
let g:bookmark_auto_close = 1
let g:bookmark_location_list = 0
highlight BookmarkSign ctermbg=NONE ctermfg=160
highlight BookmarkLine ctermbg=194 ctermfg=NONE
let g:bookmark_sign = '🔖'
let g:bookmark_highlight_lines = 1

"==============================================================================
"  Konfekt/FastFold插件配置
"==============================================================================
" 当折叠或打开折痕（zo，za，zc等）时
" 折叠或移动时（zj，zk，[z，] z）
nmap zuz <Plug>(FastFoldUpdate)
let g:fastfold_savehook = 1
" 只要你通过一个标准的按键关闭或开启褶皱如zx，zo或zc  或z+以下关键字
let g:fastfold_fold_command_suffixes =  ['x','X','a','A','o','O','c','C']
let g:fastfold_fold_movement_commands = [']z', '[z', 'zj', 'zk']

let g:markdown_folding = 1
let g:tex_fold_enabled = 1
let g:vimsyn_folding = 'af'
let g:xml_syntax_folding = 1
let g:javaScript_fold = 1
let g:sh_fold_enabled= 7
let g:ruby_fold = 1
let g:perl_fold = 1
let g:perl_fold_blocks = 1
let g:r_syntax_folding = 1
let g:rust_fold = 1
let g:php_folding = 1

"==============================================================================
"  mhinz/vim-startify插件配置
"==============================================================================
" set viminfo='100,n$HOME/.vim/files/info/viminfo

"==============================================================================
"  tpope/vim-surround插件配置
"==============================================================================
"It's easiest to explain with examples. Press cs"' inside

" \"Hello world!"
" to change it to

" 'Hello world!'
" Now press cs'<q> to change it to

" <q>Hello world!</q>
" To go full circle, press cst" to get

"\" Hello world!"
" To remove the delimiters entirely, press ds".

" Hello world!
" Now with the cursor on \"Hello", press ysiw] (iw is a text object).

" [Hello] world!
" Let's make that braces and add some space (use } instead of { for no space): cs]{

" { Hello } world!
" Now wrap the entire line in parentheses with yssb or yss).

" ({ Hello } world!)
" Revert to the original text: ds{ds)

" Hello world!
" Emphasize hello: ysiw<em>

" <em>Hello</em> world!
" Finally, let's try out visual mode. Press a capital V (for linewise visual mode) followed by S<p class="important">.

" <p class="important">
  " <em>Hello</em> world!
" </p>
" This plugin is very powerful for HTML and XML editing, a niche which currently seems underfilled in Vim land. (As opposed to HTML/XML inserting, for which many plugins are available). Adding, changing, and removing pairs of tags simultaneously is a breeze.

" The . command will work with ds, cs, and yss if you install repeat.vim.

"==============================================================================
"  puremourning/vimspector插件配置
"==============================================================================
" mnemonic 'di' = 'debug inspect' (pick your own, if you prefer!)

" Vimspector 预设了vscode mode 和 human mode 两套键盘映射（快捷键）
" vscode model
" | Key             | Mapping                                 | Function
" | ---             | ---                                     | ---
" | `F5`            | `<Plug>VimspectorContinue`              | When debugging, continue. Otherwise start debugging.
" | `Shift F5`      | `<Plug>VimspectorStop`                  | Stop debugging.
" | `Ctrl Shift F5` | `<Plug>VimspectorRestart`               | Restart debugging with the same configuration.
" | `F6`            | `<Plug>VimspectorPause`                 | Pause debuggee.
" | `F9`            | `<Plug>VimspectorToggleBreakpoint`      | Toggle line breakpoint on the current line.
" | `Shift F9`      | `<Plug>VimspectorAddFunctionBreakpoint` | Add a function breakpoint for the expression under cursor
" | `F10`           | `<Plug>VimspectorStepOver`              | Step Over
" | `F11`           | `<Plug>VimspectorStepInto`              | Step Into
" | `Shift F11`     | `<Plug>VimspectorStepOut`               | Step out of current function scope
"
" Human Mode
" | Key          | Mapping                                       | Function
" | ---          | ---                                           | ---
" | `F5`         | `<Plug>VimspectorContinue`                    | When debugging, continue. Otherwise start debugging.
" | `F3`         | `<Plug>VimspectorStop`                        | Stop debugging.
" | `F4`         | `<Plug>VimspectorRestart`                     | Restart debugging with the same configuration.
" | `F6`         | `<Plug>VimspectorPause`                       | Pause debuggee.
" | `F9`         | `<Plug>VimspectorToggleBreakpoint`            | Toggle line breakpoint on the current line.
" | `<leader>F9` | `<Plug>VimspectorToggleConditionalBreakpoint` | Toggle conditional line breakpoint or logpoint on the current line.
" | `F8`         | `<Plug>VimspectorAddFunctionBreakpoint`       | Add a function breakpoint for the expression under cursor
" | `<leader>F8` | `<Plug>VimspectorRunToCursor`                 | Run to Cursor
" | `F10`        | `<Plug>VimspectorStepOver`                    | Step Over
" | `F11`        | `<Plug>VimspectorStepInto`                    | Step Into
" | `F12`        | `<Plug>VimspectorStepOut`                     | Step out of current function scope

"
let g:vimspector_enable_mappings = 'VISUAL_STUDIO'
" for normal mode - the word under the cursor
nmap <Leader>di <Plug>VimspectorBalloonEval
" for visual mode, the visually selected text
xmap <Leader>di <Plug>VimspectorBalloonEval
" vimspector 自动安装调试组件
let g:vimspector_install_gadgets = [ 'debugpy', 'vscode-cpptools', 'vscode-go','vscode-java-debug' ]



"==============================================================================
" ludovicchabant/vim-gutentags 自动异步生成 tags 插件配置
"==============================================================================


" gutentags搜索工程目录的标志，碰到这些文件/目录名就停止向上一级目录递归 "
let g:gutentags_project_root = ['.root', '.svn', '.git', '.project']
 
" 所生成的数据文件的名称 "
let g:gutentags_ctags_tagfile = '.tags'
 
" 将自动生成的 tags 文件全部放入 ~/.cache/tags 目录中，避免污染工程目录 "
let s:vim_tags = expand('~/.cache/tags')
let g:gutentags_cache_dir = s:vim_tags
" 检测 ~/.cache/tags 不存在就新建 "
if !isdirectory(s:vim_tags)
   silent! call mkdir(s:vim_tags, 'p')
endif
 
" 配置 ctags 的参数 "
let g:gutentags_ctags_extra_args = ['--fields=+niazS', '--extra=+q']
let g:gutentags_ctags_extra_args += ['--c++-kinds=+pxI']
let g:gutentags_ctags_extra_args += ['--c-kinds=+px']

"==============================================================================
"  其他插件配置
"==============================================================================


" ctags 设置
" cd /usr/lib/go/src
" sudo ctags –R *  


set tags=./tags,/usr/lib/go/src/tags,$GOPATH/pkg/mod/tags
" 自动设置当前编辑文件路径为工作路径
" set autochdir



" markdwon 的快捷键
map <silent> <F5> <Plug>MarkdownPreview
map <silent> <F6> <Plug>StopMarkdownPreview

" tab 标签页切换快捷键
:nn <Leader>1 1gt
:nn <Leader>2 2gt
:nn <Leader>3 3gt
:nn <Leader>4 4gt
:nn <Leader>5 5gt
:nn <Leader>6 6gt
:nn <Leader>7 7gt
:nn <Leader>8 8gt
:nn <Leader>9 8gt
:nn <Leader>0 :tablast<CR>
" 新建一个标签页
noremap <space>tc :tabe<CR>
" 移至左侧标签页
noremap <space>th :-tabnext<CR>
" 移至右侧标签页
noremap <space>tl :+tabnext<CR>
" 将当前标签页向左移动一格
noremap <space>tmh :-tabmove<CR>
" 将当前标签页向右移动一格
noremap <space>tml :+tabmove<CR>

" 文件编辑快捷键
" 重新载入当前文件
noremap <space>ef :e<CR>
" 放弃修改，强制重新载入
noremap <space>eff :e<CR>
" 重新载入所有打开的文件
noremap <space>efa :e<CR>

noremap <space>p :terminal<CR>


set mouse=a     "启用鼠标"
"tmux 与vim配色不一致导致vim失色问题 
"set term=screen

" 自动跳转到上次光标所在位置
if has("autocmd")
  au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif



" 关闭其他buf
command! BcloseOthers call BufCloseOthers()
function! BufCloseOthers()

let l:currentBufNum   = bufnr("%")

let l:alternateBufNum = bufnr("#")

for i in range(1,bufnr("$"))

if buflisted(i)

if i!=l:currentBufNum

execute("bdelete ".i)

endif

endif

endfor

endfunction

noremap <space>wbc :BcloseOthers<CR>
